package com.learn.fourday;

import org.apache.log4j.Logger;

/**
 * 两个线程对初始值为0的静态变量一个做自增，一个做自减，各自5000此，结果是0吗？
 *
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/10
 */
public class ShareValueTest {

    private static final Logger logger = Logger.getLogger(ShareValueTest.class);


    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            room.increment();
        }, "t1");

        Thread t2 = new Thread(() -> {
            room.decrement();
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        logger.debug("counter:" + room.getCounter());

    }

}

class Room{
    private int counter=0;

    public void increment(){
        synchronized (this){
            counter++;
        }
    }

    public void decrement(){
        synchronized (this){
            counter--;
        }
    }

//    public synchronized void decrement(){
//        synchronized (this){
//            counter--;
//        }
//    }


    public int getCounter(){
        synchronized (this){
            return counter;
        }
    }
}
